<template>
  <div class="add-address-page">
    <div class="nav-bar">
      <van-nav-bar title="新增收货地址" left-text="" right-text="" left-arrow @click-left="onClickLeft" />
    </div>
    <div class="add-address-box">
      <van-address-edit :area-list="areaList" :address-info='addressInfo' :is-saving="false" show-set-default @save="onSave" />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Area, AddressEdit, Toast } from 'vant'
import areaList from '#/common/js/area'
import {CODE, APIURI} from '#/common/js/apiConst'
Vue.use(NavBar)
  .use(AddressEdit)
  .use(Area)
export default {
  data() {
    return {
      areaList,
      addressInfo: {}
    }
  },
  mounted() {
    this.changeCSS()
  },
  methods: {
    onClickLeft() {
      this.routeParam('/user/addresslist')
    },

    onSave() {
      let param = JSON.parse(JSON.stringify(this.addressInfo))
      param = Object.assign(this.returnForm(param), { uid: '2' })
      param = this.serializeParam(param)
      this.$axios
        .post(APIURI + '/address/add', param, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })
        .then(res => {
          res = res.data
          if (res.code === CODE) {
            Toast('保存成功')
            this.onReturn()
          }
        })
        .catch(function(err) {
          console.log(err)
        })
    },
    onReturn() {
      this.routeParam('/user/addresslist')
    },
    routeParam(url) {
      let source = this.$route.query.source
      if (source) {
        if (url.indexOf('?') !== -1) {
          this.$router.push({ path: url + '&source=' + source })
        } else {
          this.$router.push({ path: url + '?source=' + source })
        }
      } else {
        this.$router.push({ path: url })
      }
    },
    returnForm(addressInfo) {
      addressInfo.mobile = addressInfo.tel
      addressInfo.area =
        addressInfo.province + ' ' + addressInfo.city + ' ' + addressInfo.county
      addressInfo.address = addressInfo.address_detail
      addressInfo.stats = addressInfo.is_default ? '1' : '0'
      addressInfo.code = addressInfo.area_code
      delete addressInfo.tel
      delete addressInfo.province
      delete addressInfo.city
      delete addressInfo.county
      delete addressInfo.address_detail
      delete addressInfo.area_code
      delete addressInfo.is_default

      return addressInfo
    },
    serializeParam(param) {
      let serialize = ''
      for (let key in param) {
        serialize += key + '=' + param[key] + '&'
      }
      serialize = serialize.substr(0, serialize.length - 1)
      return serialize
    },
    changeCSS() {
      let addressLine = document.getElementsByClassName(
        'van-field--has-textarea'
      )[0]
      addressLine.classList.add('van-hairline--bottom')
    }
  }
}
</script>

<style lang="scss" scoped>
.nav-bar {
  margin-bottom: 10px;
}
</style>

